const mongo = require("../../lib/mongo");
const validate = require('koa2-validation');
const Joi = require('joi');
const ctrl = {};
ctrl.index = async (ctx) => {
    let javascript = ctx.session.userInfo ? `window.appInfo.user = ${JSON.stringify(ctx.session.userInfo)}` : '';
    await ctx.render('index', {javascript, settings:{autoescape: false}});
};
ctrl.login = async (ctx) => {
    try{
        let name = ctx.request.body.name;
        let password = ctx.request.body.password;
        const admin = new mongo(mydb, 'backend.admin');
        let userInfo = await admin.findOne({name});
        if(!userInfo) return await fun.res(ctx, '10001');
        let isEqual = fun.checkPassword(password, userInfo.pass);
        if(!isEqual) return await fun.res(ctx, '10001');
        delete userInfo.pass;
        ctx.session.userInfo = userInfo;
        return await fun.res(ctx, '00000', userInfo);
    }catch(e){
        throw e;
    }
};
ctrl.logout = async (ctx) => {
    try{
        delete ctx.session.userInfo;
        return await fun.res(ctx, '00000');
    }catch(e){
        throw e;
    }
};
module.exports = (_, pre = '/vino/') =>{
    _.get(pre, ctrl.index);
    _.post(pre + 'api/login', validate({
        body: {
            name: Joi.string().required(),
            password: Joi.string().required()
        }
    }), ctrl.login);
    _.get(pre + 'api/logout', ctrl.logout);
};